#include <qmessagebox.h>
#include <qfiledialog.h>

#include "SetupDialog.h"

SetupDialog::SetupDialog(QWidget * parent): QDialog(parent)
{
	ui.setupUi(this);

	connect(ui.confirm, &QPushButton::clicked, this, &SetupDialog::onConfirmClicked);
	connect(ui.radioInTurn, &QRadioButton::clicked, this, &SetupDialog::onInturnClicked);
	connect(ui.radioSingle, &QRadioButton::clicked, this, &SetupDialog::onSingleClicked);
	connect(ui.browse1, &QPushButton::clicked, this, &SetupDialog::onBrowse1Clicked);
	connect(ui.browse2, &QPushButton::clicked, this, &SetupDialog::onBrowse2Clicked);
}

void SetupDialog::onConfirmClicked()
{
	QString engine1Path = ui.engine1Path->text();
	QString engine2Path = ui.engine2Path->text();

	if (engine1Path == "" || engine2Path == "")
	{
		QMessageBox::critical(this, "error", "the path of the engines must not be empty!");
		return;
	}

	int time = ui.timeText->text().toInt();
	if (time <= 0 || time > 20)
	{
		QMessageBox::critical(this, "error", "the simulation time must be an integer within (0, 20]!");
		return;
	}

	int mode;
	if (ui.radioInTurn->isChecked())
	{
		mode = 1;
	}
	else if (ui.radioSingle->isChecked())
	{
		mode = 2;
	}

	int first = ui.firstText->text().toInt();
	if (mode == 2 && first != 1 && first != 2)
	{
		QMessageBox::critical(this, "error", "the first to play must be 1 or 2!");
		return;
	}

	emit sendData(engine1Path, engine2Path, time, mode, first);
	this->close();
}

void SetupDialog::onInturnClicked()
{
	ui.firstText->setEnabled(false);
}

void SetupDialog::onSingleClicked()
{
	ui.firstText->setEnabled(true);
}

void SetupDialog::onBrowse1Clicked()
{
	QString path = QFileDialog::getOpenFileName(this, "open engine");
	ui.engine1Path->setText(path);
}

void SetupDialog::onBrowse2Clicked()
{
	QString path = QFileDialog::getOpenFileName(this, "open engine");
	ui.engine2Path->setText(path);
}